from django.core.cache import cache
from django.db.models import Q
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from course.couserializer import CourseSer, CateSerializer, CategorySer, CourseSerializer, CourseSerSer, ChapteSer, \
    CourseSearchSerializer
from course.models import Category, Course, CourseTags, Teacher, Lession, Chapter
from drf_haystack.viewsets import HaystackViewSet


# 查询全部
class CourseViews(APIView):
    def get(self,request):
        data = Category.objects.filter(isdel=False,parent=None).order_by('sort')
        ser = CourseSer(data,many=True)
        all_data = ser.data
        for i in all_data:
            i['children'] = i['children'][:3]
        return Response({
            "msg":"ok",
            "data":ser.data
        })

# 父类查子类的子类
class TestCate(APIView):
    def get(self,request):
        data = Category.objects.filter(isdel=False, parent=None).order_by("sort")
        ser=CateSerializer(data,many=True)
        return Response({"msg":"ok","data":ser.data})


# 父类查子类
class HomeChild(APIView):
    def get(self,request):
        parent = request.query_params.get('parent')
        if not parent:
            return Response({"msg": "一级分类id不能为空", "code": 400})
        info = Category.objects.filter(isdel=False, id=parent).first()
        ser=CourseSer(info)
        return Response({"msg":"ok","data":ser.data})


class OneCate(APIView):
    def get(self,request):
        data = Category.objects.filter(isdel=False, parent=None).order_by("sort")
        ser=CategorySer(data,many=True)
        return Response({"msg":"ok","data":ser.data})


class TwoCate(APIView):
    def get(self,request):
        direction = request.query_params.get('direction',"0")
        if direction == "0":
            data = Category.objects.filter(isdel=False, parent__isnull = False).order_by("sort")
        else:
            data = Category.objects.filter(isdel=False, parent = direction).order_by("sort")
        ser=CategorySer(data,many=True)
        return Response({"msg":"ok","data":ser.data})

class CoursePage(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 100
    page_query_param = 'page'

# 课程列表展示
class CourseList(ListAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer
    pagination_class = CoursePage
    def get_queryset(self):
        # 默认的条件 isdel=False
        query = Q(isdel=False)
        # 探索有两个条件  direction 一级分类  和 category  二级分类
        direction = self.request.query_params.get('direction', "0")
        category = self.request.query_params.get('category', "0")
        ordering = self.request.query_params.get('ordering', "")
        nav = self.request.query_params.get('nav', "")
        # 一级分类不为0 二级分类为0
        if direction != "0" and category == "0":
            # 应该根据方向找到都有的子类  呈现形式为[1，2，3]
            child = Category.objects.filter(parent=direction).values_list('id', flat=True)
            # 找到所有子类下的课程
            query &= Q(category__in=child)
        # 一级分类和二级分类都不为0
        if category != "0":
            # 找到所有子类下的课程
            query &= Q(category=category)
        # 顶部导航限制
        if nav:
            query &= Q(nav=nav)
        # 排序
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        return self.queryset.filter(query)

class Detail(APIView):
    def get(self,request):
        id = request.query_params.get('id')
        if not id:
            return Response({"msg": "课程id不能为空", "code": 400})
        info = Course.objects.filter(isdel=False, id=id).first()

        ser = CourseSerSer(info)
        tag = CourseTags.objects.filter(course=id).values('tags__name')
        data = ser.data
        data['tags'] = []
        for i in tag:
            data['tags'].append(i['tags__name'])
        return Response({"code":200,"msg":"ok","data":data})


class Chapters(APIView):
    def get(self,request):
        id = request.query_params.get('id')
        if not id:
            return Response({"msg": "课程id不能为空", "code": 400})
        chapter = Chapter.objects.filter(course_id=id,isdel=False).order_by('sort')
        ser = ChapteSer(chapter,many=True)
        return Response({"msg":"ok","data":ser.data,"code":200})



class SearchView(HaystackViewSet):
    index_models=[Course]#mysql orm的模型类
    serializer_class=CourseSearchSerializer#索引的序列化器类
    pagination_class = CoursePage#分页类

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        # 获取到搜索关键字
        word = request.query_params.get('text')
        isyes = False
        # 获取到热词的存储数据
        wordlist = cache.get('hotword',[])
        #[{"word":"python","count":50},{}]
        # 判断关键词是否在热词列表中
        for item in wordlist:
            if item['word'] == word:
                item['count'] += 1
                isyes = True
                break
        if not isyes:
            # 如果不在热词列表中，添加到列表
            wordlist.append({"word":word,"count":1})
        # 缓存热词列表
        cache.set('hotword',wordlist,60*60*24)
        response = super().list(request, *args, **kwargs)
        return response


# 热词列表
class HotWord(APIView):
    def get(self,request):
        # 获取到热词的存储数据
        wordlist = cache.get('hotword',[])
        # 返回按照count排序的前五名
        wordlist = sorted(wordlist,key=lambda x:x['count'],reverse=True)[:5]
        # 返回数据
        return Response({"msg":"ok","data":wordlist,"code":200})











